<?php

namespace App\Tcp;

use EasySwoole\EasySwoole\ServerManager;

class Message extends Base
{

    /**
     * 接收数据处理
     */
    public static function recieve($param, $fd)
    {
        if (!($userType = $param['user_type'] ?? '') || !in_array($userType, [1, 2])) return false;
        switch ($userType) {
            case 1:
                if (!($receiveUid = $param['receive_uid'] ?? '')) return false;
                if (self::send($param, $receiveUid)) return true;
                return false;
                break;

            case 2:
                if (!($groupId = $param['group_id'] ?? '')) return false;
                self::sendAll($param, $groupId, $fd);
                break;
            
            default:
                break;
        }
    }

    /**
     * 发送单聊
     */
    public static function send($param, $receiveUid)
    {
        $redis = self::redis();
        if (!$fd = $redis->hGet(self::TCP_LOGIN_KEY, $receiveUid)) return false;
        $server = ServerManager::getInstance()->getSwooleServer();
        if ($server->send($fd, self::successJSON($param))) return true;
        return false;
    }

    /**
     * 发送群聊
     */
    public static function sendAll($param, $groupId, $sendFd)
    {
        $redis = self::redis();
        if (!$userList = $redis->sMembers(self::USER_GROUP_KEY.$groupId)) return false;
        $server = ServerManager::getInstance()->getSwooleServer();
        foreach ($userList as $user) {
            if (($fd = $redis->hGet(self::TCP_LOGIN_KEY, $user)) && ($fd != $sendFd)) $server->send($fd, self::successJSON($param));
        }
        return true;
    }
    // {"request_type":1, "param":{"uid":123}}
    // {"request_type":1, "param":{"uid":321}}
    // {"request_type":2, "param":{"send_uid":123, "receive_uid":321, "user_type":1, "message_type":1, "content":"测试测试"}}
    // {"request_type":2, "param":{"send_uid":321, "receive_uid":123, "user_type":1, "message_type":1, "content":"test_test"}}
    // {"request_type":2, "param":{"send_uid":123, "group_id":100, "user_type":2, "message_type":1, "content":"测试测试"}}
    // {"request_type":3, "param":{"uid":123, "group_id":100}}
    // {"request_type":3, "param":{"uid":321, "group_id":100}}

}